package com.hoshiicloud.shxping.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.constant.DeleteStatusEnum;
import com.hoshiicloud.common.controller.BaseController;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.shxping.feign.IUserFeignService;
import com.hoshiicloud.shxping.feign.OrderFeignService;
import com.hoshiicloud.shxping.param.CartAddParam;
import com.hoshiicloud.shxping.param.CartDeleteParam;
import com.hoshiicloud.shxping.param.CartQueryParam;
import com.hoshiicloud.shxping.param.CartUpdateParam;
import com.hoshiicloud.shxping.vo.CartDetailVO;
import com.hoshiicloud.shxping.vo.CartVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yangcheng
 * @version 1.0
 * @title: CartController
 * @description: 购物车Controller
 * @date 2019/6/6 18:03
 * @mail maiboyc@163.com
 */
@Slf4j
@RestController
@RequestMapping("/cart")
@Api(value = "购物车管理", tags = {"购物车相关操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class CartController extends BaseController {

    // 订单微服务Service
    @Resource
    private OrderFeignService orderFeignService;

    // 用户微服务Service
    @Resource
    private IUserFeignService userFeignService;

    /**
     * 加入购物车
     * @param param 加入购物车参数
     * @return Response
     */
    @PostMapping("/add")
    @ApiOperation(value = "加入购物车", notes = "加入购物车", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response add(@RequestBody CartAddParam param) {
        Response rs;
        try {
            rs = orderFeignService.add(param);
        } catch (Exception e) {
            log.error("加入购物车异常"+"["+e.getMessage()+"]");
            rs = Response.failed("加入购物车异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 修改购物车购物信息
     * @param param 更新购物车参数
     * @return Response
     */
    @PostMapping("update")
    @ApiOperation(value = "修改购物车购物信息", notes = "修改购物车购物信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response update(@RequestBody CartUpdateParam param) {
        Response rs;
        try {
            rs = orderFeignService.update(param);
        } catch (Exception e) {
            log.error("加入购物车异常"+"["+e.getMessage()+"]");
            rs = Response.failed("加入购物车异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 更新购物车商品失效状态
     * @param userId 用户ID
     * @return Response
     */
    @PostMapping("updateCartStatus")
    @ApiOperation(value = "更新购物车商品失效状态", notes = "更新购物车商品失效状态", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response updateCartStatus(@RequestParam String userId) {
        Response rs;
        try {
            rs = orderFeignService.updateCartStatus(userId);
        } catch (Exception e) {
            log.error("更新购物车商品失效状态异常"+"["+e.getMessage()+"]");
            rs = Response.failed("更新购物车商品失效状态异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 删除购物车购物信息
     * @param id 购物车ID
     * @return Response
     */
    @DeleteMapping("delete/{id}")
    @ApiOperation(value = "删除购物车购物信息记录表", notes = "删除购物车购物信息记录表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response delete(@PathVariable("id") String id) {
        Response rs;
        try {
            rs = orderFeignService.delete(id);
        } catch (Exception e) {
            log.error("删除购物车购物信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed("删除购物车购物信息异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 批量删除购物车购物信息记录表
     * @param ids 购物车IDS
     * @return Response
     */
    @PostMapping("deleteByIds")
    @ApiOperation(value = "批量删除购物车购物信息", notes = "批量删除购物车购物信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response deleteByIds(@RequestParam List<Long> ids) {
        Response rs;
        try {
            rs = orderFeignService.deleteByIds(ids);
        } catch (Exception e) {
            log.error("批量删除购物车购物信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed("批量删除购物车购物信息异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 根据用户ID和店铺ID批量删除购物车购物信息
     * @param param 删除参数
     * @return Response
     */
    @DeleteMapping("deleteByUserIdAndStoreId")
    @ApiOperation(value = "根据用户ID和店铺ID批量删除", notes = "根据用户ID和店铺ID批量删除购物车购物信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response deleteByUserIdAndStoreId(@RequestBody CartDeleteParam param) {
        Response rs;
        try {
            rs = orderFeignService.deleteByUserIdAndStoreId(param.getUserId(),param.getStoreId());
        } catch (Exception e) {
            log.error("根据用户ID和店铺ID批量删除购物车购物信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed("根据用户ID和店铺ID批量删除购物车购物信息异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 获取购物车购物信息详情
     * @param id 购物车ID
     * @return Response<CartDetailVO>
     */
    @PostMapping("getDetail")
    @ApiOperation(value = "获取购物车购物信息详情", notes = "获取购物车购物信息详情", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<CartDetailVO> getDetail(@RequestParam("id") String id) {
        Response<CartDetailVO> rs;
        try {
            rs = orderFeignService.getDetail(id);
        } catch (Exception e) {
            log.error("获取购物车购物信息详情异常"+"["+e.getMessage()+"]");
            rs = Response.failed("获取购物车购物信息详情异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 获取购物车购物信息列表
     * @param param 参数
     * @return Response
     */
    @PostMapping("getList")
    @ApiOperation(value = "获取购物车购物信息列表", notes = "获取购物车购物信息列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<List<CartVO>> getList(@RequestBody CartQueryParam param) {
        Response<List<CartVO>> rs;
        try {
            param.setDeleted(DeleteStatusEnum.UN_DELETED.getCode());//未删除的购物车列表
            rs = orderFeignService.getList(param);
        } catch (Exception e) {
            log.error("获取购物车购物信息列表异常"+"["+e.getMessage()+"]");
            rs = Response.failed("获取购物车购物信息列表异常"+e.getMessage());
        }
        return rs;
    }

    /**
     * 分页获取购物车购物信息列表
     * @param param 分页参数
     * @return Response<IPage<CartVO>>
     */
    @PostMapping("getPage")
    @ApiOperation(value = "分页获取购物车购物信息列表", notes = "分页获取购物车购物信息列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Page<Map<String,Object>>> getPage(@RequestBody CartQueryParam param) {
        Response<Page<Map<String,Object>>> rs = new Response<>();
        try {
            param.setDeleted(DeleteStatusEnum.UN_DELETED.getCode());
            Response<Page<CartVO>> result = orderFeignService.getPage(param);
            Page<Map<String,Object>> page = new Page<>();
            if (null != result && result.getCode() == 200 && result.getData().getRecords().size() > 0) {
                // 以storeId分组
                Map<Long, List<CartVO>> groupCartMap = result.getData().getRecords().stream().collect(Collectors.groupingBy(CartVO::getStoreId));
                // 组装最终返回数据Map<String,Object>
                page.setCurrent(result.getData().getCurrent());
                page.setPages(result.getData().getPages());
                page.setSearchCount(result.getData().isSearchCount());
                page.setSize(result.getData().getSize());
                page.setTotal(result.getData().getTotal());
                List<Map<String,Object>> list = new ArrayList<>();
                if (null != groupCartMap && groupCartMap.keySet().size() >0) {
                    groupCartMap.keySet().forEach(item ->{
                        Map<String,Object> map = new HashMap<>();
                        map.put("storeId",item);
                        map.put("storeName",userFeignService.queryById(item).getData().getStoreName());
                        map.put("cartVO", groupCartMap.get(item));
                        list.add(map);
                    });
                }
                page.setRecords(list);
            }
            rs.setData(page);
            rs.setCode(result != null ? result.getCode() : null);
            rs.setMsg(result != null ?  result.getMsg() : null);
        } catch (Exception e) {
            log.error("分页获取购物车购物信息列表异常"+"["+e.getMessage()+"]");
            rs = Response.failed("分页获取购物车购物信息列表异常"+e.getMessage());
        }
        return rs;
    }

}
